import { create } from 'zustand'
import { persist } from 'zustand/middleware'

interface AppState {
  count: number
  increment: () => void
  decrement: () => void
  reset: () => void
  user: null | { name: string; email: string }
  setUser: (user: { name: string; email: string }) => void
  isLoggedIn: boolean
  tokenInfo: null | {
    access_token: string
    token_type: string | null
    expires_in: number
    refresh_token: string
  }
  setTokenInfo: (tokenInfo: {
    access_token: string
    token_type: string | null
    expires_in: number
    refresh_token: string
  }) => void
  login: (username: string, password: string) => Promise<void>
  logout: () => void
}

export const useStore = create<AppState>()(
  persist(
    (set) => ({
      count: 0,
      increment: () => set((state) => ({ count: state.count + 1 })),
      decrement: () => set((state) => ({ count: state.count - 1 })),
      reset: () => set({ count: 0 }),
      user: null,
      setUser: (user) => set({ user }),
      isLoggedIn: false,
      tokenInfo: null,
      setTokenInfo: (tokenInfo) => {
        set({ isLoggedIn: true })
        set({ tokenInfo })
      },
      login: async (username, password) => {
        // 这里应该调用API进行登录验证
        // 模拟登录成功
        set({ isLoggedIn: true })
      },
      logout: () => set({ 
        isLoggedIn: false, 
        user: null,
        tokenInfo: null 
      })
    }),
    {
      name: 'app-storage',
      storage: {
        getItem: (name) => {
          const str = localStorage.getItem(name)
          return str ? JSON.parse(str) : null
        },
        setItem: (name, value) => {
          localStorage.setItem(name, JSON.stringify(value))
        },
        removeItem: (name) => {
          localStorage.removeItem(name)
        },
      },
    }
  )
)
